<template>
  <div class="back-to-top" v-if="showButton" @click="scrollToTop">
    <div class="back-icon">↑</div>
  </div>
</template>

<script>
export default {
  name: 'BackToTop',
  data() {
    return {
      showButton: false,
      scrollTimer: null
    }
  },
  mounted() {
    this.bindScrollEvent()
  },
  beforeDestroy() {
    this.unbindScrollEvent()
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer)
    }
  },
  methods: {
    checkScrollPosition() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop
      // 当滚动超过300px时显示按钮
      this.showButton = scrollTop > 300
    },
    bindScrollEvent() {
      window.addEventListener('scroll', this.handleScroll)
    },
    unbindScrollEvent() {
      window.removeEventListener('scroll', this.handleScroll)
    },
    handleScroll() {
      // 防抖处理
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer)
      }
      this.scrollTimer = setTimeout(() => {
        this.checkScrollPosition()
      }, 100)
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    }
  }
}
</script>

<style scoped>
.back-to-top {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 50px;
  height: 50px;
  background: rgba(0, 0, 0, 0.8);
  border: 1px solid rgba(0, 212, 255, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 999;
  transition: all 0.3s ease;
  animation: fadeIn 0.3s ease;
}

.back-to-top:hover {
  background: rgba(0, 212, 255, 0.1);
  border-color: #00d4ff;
  transform: translateY(-2px);
}

.back-icon {
  font-size: 20px;
  color: #00d4ff;
  font-weight: bold;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .back-to-top {
    bottom: 20px;
    right: 20px;
    width: 45px;
    height: 45px;
  }
  
  .back-icon {
    font-size: 18px;
  }
}
</style>
